//
//  ComposeViewController.swift
//  weiboLQ
//
//  Created by 半缘君 on 15/12/16.
//  Copyright © 2015年 banyuanjun.cn. All rights reserved.
//

import UIKit
import SVProgressHUD
class ComposeViewController: UIViewController {
    
/// 懒加载表情键盘
    private lazy var emotIconKeyBoard:LQEmotIconKeyboard = LQEmotIconKeyboard {[weak self] (em) -> () in
        self?.textV.insertEmoticon(em)
    }
    @objc private func selectPictures () {
//        print("选择图片")
        if picturePikerVc.view.bounds.height != 0 {
            return
        }
        //取消键盘
        textV.resignFirstResponder()
        
        //设置图片选择view的高度
        picturePikerVc.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        //设置textView的frame
        textV.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(picturePikerVc.view.snp_top)
        }
        //动画
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    @objc private func selectEmoticon () {
        //退下当前键盘
        textV.resignFirstResponder()
        //更换键盘
        textV.inputView = textV.inputView == emotIconKeyBoard ? nil : emotIconKeyBoard
        //叫出键盘
        textV.becomeFirstResponder()
    }
/// 发布微博
    @objc private func sendStatus () {
        SVProgressHUD.show()
        let image = picturePikerVc.selectedPictures.first
        NetworkTools.shareNetworkTools.sentStatus(textV.text,image:image) { (result, error) -> Void in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力...")
                print(error)
                return
            }
            SVProgressHUD.showSuccessWithStatus("发布成功")
            
            self.close()
            SVProgressHUD.dismiss()
            
        }
    }
/// 关闭发布页面
    @objc private func close () {
        textV.resignFirstResponder()
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //MARK: - 生命周期方法
    override func loadView() {
        super.loadView()
        view.backgroundColor = UIColor.whiteColor()

        setupUI()
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    override func viewDidAppear(animated: Bool) {

        super.viewDidAppear(animated)
        if  picturePikerVc.view.frame.height == 0{
        textV.becomeFirstResponder()
        }
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        textV.resignFirstResponder()
    }
    //键盘frame变化执行函数
   @objc private func keyBoardChangeFrame (not:NSNotification) {
//        print(not.userInfo)
        let rect = not.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue

    let duration = not.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
    // 动画曲线数值
    let curve = (not.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
    
    let bottomDistance = -UIScreen.mainScreen().bounds.height + rect.origin.y
    
    toolBar.snp_updateConstraints { (make) -> Void in
        make.bottom.equalTo(view.snp_bottom).offset(bottomDistance)
    }
    //动画
    UIView.animateWithDuration(duration) { () -> Void in
        
        UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
        
       self.view.layoutIfNeeded()
    }
        
    }
    
    //MARK: - 懒加载控件
    private lazy var textV:UITextView = {
        
       let tv = UITextView()
        tv.alwaysBounceVertical = true
//        tv.text = "新鲜事..."
        tv.font = UIFont.systemFontOfSize(14)
        return tv
    }()
    private lazy var placeHoderView:UILabel = UILabel(txt: "新鲜事...")
    private lazy var titleView:UIView = UIView()
    private lazy var upLabel:UILabel = UILabel(txt: "发布微博", txtFont: 15,alignment:NSTextAlignment.Center)
    //        upLabel.backgroundColor = UIColor.greenColor()
    private lazy var downLabel:UILabel = UILabel(txt: UserAccountViewModel.shareAccountModel.account?.screenName ?? "", txtFont: 15, txtColor: UIColor.lightGrayColor(),alignment:NSTextAlignment.Center)
    private lazy var toolBar = UIToolbar()
    private lazy var picturePikerVc:LQPictureViewController = LQPictureViewController()
}
// MARK: - 设置UI
extension ComposeViewController {
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        //辞去第一响应者
        textV.resignFirstResponder()
    }
    
    /// 添加占位Label
    private func addPlaceHoderView () {
        textV.addSubview(placeHoderView)
        placeHoderView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textV.snp_top).offset(7)
            make.left.equalTo(textV.snp_left).offset(5)
        }
    }
    /// 设置UI
    private func setupUI () {
        //添加items
        addBarButtonItems()
        //添加titleView
        addTitleView()
        //添加toolBar
        addToolbar()
        //添加textView
        addTextView()
        //添加picturePickerView
        addPicturePicker()
    }
    ///添加图片选择控制器的view
    private func addPicturePicker () {
        //添加子控制器
        addChildViewController(picturePikerVc)
        automaticallyAdjustsScrollViewInsets = false
        view.insertSubview(picturePikerVc.view, belowSubview: toolBar)
        picturePikerVc.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.height.equalTo(0)
        }
        
    }
    
    ///添加textView
    private func addTextView () {
        
        view.addSubview(textV)
        //添加占位Label
        addPlaceHoderView()
        textV.delegate = self
        textV.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
    }
    /// 添加toolBar
    private func addToolbar () {
        view.addSubview(toolBar)
//        toolBar.tintColor = UIColor.clearColor()
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.width.equalTo(view.snp_width)
            make.height.equalTo(44)
        }
        
        addToolBarItem()
    }
/// 添加toolBarItem
    private func addToolBarItem () {
        
        let itemSettings = [["imageName": "compose_toolbar_picture",
                            "actionName": "selectPictures"],
                        ["imageName": "compose_mentionbutton_background"],
                        ["imageName": "compose_trendbutton_background"],
                        ["imageName": "compose_emoticonbutton_background",
                        "actionName": "selectEmoticon"],
                        ["imageName": "compose_addbutton_background"]]
        
    var items = [UIBarButtonItem]()
        for dict in itemSettings {
        items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))

            let toolBtn = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(toolBtn)
            
        }
        items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        toolBar.items = items
    }
    
    /// 添加items
    private func addBarButtonItems () {
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
}
    
    /// 添加titleView
    private func addTitleView () {
        
        titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 36)

        titleView.addSubview(upLabel)
        titleView.addSubview(downLabel)
        
        upLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
//            make.left.equalTo(titleView.snp_left)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        downLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
//            make.left.equalTo(titleView.snp_left)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        navigationItem.titleView = titleView
    }
}
// MARK: - UITextViewDelegate 代理方法
extension ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textV.hasText()
        placeHoderView.hidden = textV.hasText()
        
    }
}